using Core.SimpleTemp.Application;
using Core.SimpleTemp.Common.Authorization;
using Core.SimpleTemp.Common.PagingQuery;
using Core.SimpleTemp.Mvc.Api.Internal;
using Core.Toolkit.Authorization;
using Core.Toolkit.Core;
using Core.Toolkit.Core.Api;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Threading.Tasks;
using System.Linq;
using System.Collections.Generic;
using Core.SimpleTemp.Entitys;

namespace Core.SimpleTemp.Api.Api
{
    /// <summary>
    /// YH_Screening
    ///</summary>
    [ApiExplorerSettings(GroupName = "YH")]//swagger分类标签
    [Route("api/[controller]")]//路由说明
    [EnableCors("any")]//跨域规则
    [ApiController]//APi标识Controller
    [Authorize]//验证是否登录
    public class YH_ScreeningController : CoreApiController
    {
        private readonly YH_ScreeningService _service;
        private readonly YH_ScreeningDetailService _serviceDetail;
        private readonly YH_ScreeningPlanService _servicePlan;
        /// <summary>
        /// YH_Screening
        ///</summary>
        public YH_ScreeningController(YH_ScreeningService service, YH_ScreeningPlanService servicePlan, YH_ScreeningDetailService serviceDetail)
        {
            _service = service;
            _servicePlan = servicePlan;
            _serviceDetail = serviceDetail;
        }
        /// <summary>
        /// 查询
        ///</summary>
        /// <param name="pagingQueryModel"></param>
        /// <returns></returns>

        [HttpPost("GetPlanList")]
        [PermissionFilter(nameof(YH_ScreeningController) + "_" + nameof(YH_ScreeningController.GetPlanList), AuthorizationConst.LIST)]
        public async Task<IActionResult> GetPlanList(PagingModel<YH_ScreeningPlanDto> pagingQueryModel)
        {
            pagingQueryModel.Model.ScreeningPerson = UserIdentity.Id;
            IPageModel<YH_ScreeningPlanDto> result = await _servicePlan.GetListForPC(pagingQueryModel);
            //拼接参与人员姓名
            result.PageData.ForEach(dto =>
            {
                var str = "";
                dto.YH_ScreeningPlanUser.ToList().ForEach(a =>
                {
                    str += a.UserText + ",";
                });
                if (str.Length > 0)
                    str = str.Substring(0, str.Length - 1);
                dto.Participant = str;


                dto.YH_ProjectAndDetail = new List<YH_ProjectAndDetail>();
                dto.YH_ScreeningPlanProject.ToList().ForEach(project =>
                {
                    project.YH_ScreeningPlanProDetail.ToList().ForEach(detail =>
                    {
                        dto.YH_ProjectAndDetail.Add(new YH_ProjectAndDetail()
                        {
                            ScreeningPlanId = dto.Id,
                            Project = project.Project,
                            Region = detail.Region,
                            RegionName = detail.RegionName,
                            AreaName = detail.RegionName,
                            Remark = project.Remark,
                            //SysArea = project.SysArea,
                            ScreeningPlanProjectId = project.Id,
                            ScreeningPlanProDetailId = detail.Id,
                            SearchMajorCode = detail.SearchMajorCode,
                            StandardID = detail.StandardID,
                            StandardContent = detail.StandardContent,
                            Type = detail.Type,
                            CreateFactory = detail.CreateFactory,
                            RiskLevel = detail.RiskLevel,
                            RiskLevelText = detail.RiskLevelText,

                        });
                    });
                });
            });
            return this.JsonSuccess(result);
        }
        #region 基础增删改查
        /// <summary>
        /// 查询
        ///</summary>
        /// <param name="pagingQueryModel"></param>
        /// <returns></returns>

        [HttpPost("GetList")]
        [PermissionFilter(nameof(YH_ScreeningController) + "_" + nameof(YH_ScreeningController.GetList), AuthorizationConst.LIST)]
        public async Task<IActionResult> GetList(PagingModel<YH_ScreeningDto> pagingQueryModel)
        {
            pagingQueryModel.Model.ScreeningPerson = UserIdentity.Id;
            IPageModel<YH_ScreeningDto> result = await _service.GetList(pagingQueryModel);
            //拼接参与人员姓名
            result.PageData.ForEach(dto =>
            {
                var str = "";
                dto.YH_ScreeningUser.ToList().ForEach(a =>
                {
                    str += a.UserText + ",";
                });
                if (str.Length > 0)
                    str = str.Substring(0, str.Length - 1);
                dto.Participant = str;
            });
            return this.JsonSuccess(result);
        }
        /// <summary>
        /// 添加
        ///</summary>
        /// <param name="dto"></param>
        /// <returns></returns>

        [HttpPost("Save")]
        [PermissionFilter(nameof(YH_ScreeningController) + "_" + nameof(YH_ScreeningController.SaveAsync), AuthorizationConst.SAVE)]
        public async Task<IActionResult> SaveAsync(YH_ScreeningPlanDto dto)
        {

            //参与人员
            var YH_ScreeningUserDto = new List<YH_ScreeningUserDto>();
            dto.YH_ScreeningPlanUser.ToList().ForEach(a =>
            {
                YH_ScreeningUserDto.Add(new YH_ScreeningUserDto()
                {
                    UserId = a.UserId
                });
            });
            //项目
            var YH_ScreeningProjectDto = new List<YH_ScreeningProjectDto>();
            dto.YH_ScreeningPlanProject.ToList().ForEach(a =>
            {
                var YH_ScreeningDetailDto = new List<YH_ScreeningDetailDto>();
                a.YH_ScreeningPlanProDetail.ToList().ForEach(b =>
                {
                    YH_ScreeningDetailDto.Add(new YH_ScreeningDetailDto()
                    {
                        AreaID = b.Region,
                        ClearanceProjects = a.Project,
                        CreateFactory = UserIdentity.Factory,
                        HazardTypeID = b.HazardTypeID,
                        ReportType = "0",//0计划，1非计划
                        RiskLevel = b.RiskLevel,
                        result = "未排查",//此处需做一个数据对比，用作判断是否该标准已存在整改中的
                        ScreeningPlanProDetailId = b.Id,
                        ScreeningPlanProjectId = a.Id,
                        SearchMajorCode = b.SearchMajorCode,
                        StandardContent = b.StandardContent,
                        StandardID = b.StandardID,
                        Type = b.Type,
                        IsNotPlan = true
                    });
                });


                YH_ScreeningProjectDto.Add(new YH_ScreeningProjectDto()
                {
                    Project = a.Project,
                    Remark = a.Remark,
                    YH_ScreeningDetail = YH_ScreeningDetailDto
                });
            });

            //主表
            var YH_ScreeningDto = new YH_ScreeningDto()
            {
                Status = "未开始",
                CreateFactory = UserIdentity.Factory,
                BeginTime = DateTime.Now,
                ScreeningPlanId = dto.Id,
                Unit = dto.Unit,
                Objective = dto.Objective,
                PersonInCharge = dto.PersonInCharge,
                Requirements = dto.Requirements,
                Content = dto.Content,
                StandardType = dto.StandardType,
                InvestigationPost = dto.InvestigationPost,
                YH_ScreeningUser = YH_ScreeningUserDto,
                YH_ScreeningProject = YH_ScreeningProjectDto
            };
            var entity = await _service.InsertAsync(YH_ScreeningDto);
            return this.JsonSuccess(entity?.Id);

        }

        /// <summary>
        /// 手动新增一条排查
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost("Insert")]
        [PermissionFilter(nameof(YH_ScreeningController) + "_" + nameof(YH_ScreeningController.InsertAsync), AuthorizationConst.SAVE)]
        public async Task<IActionResult> InsertAsync(YH_ProjectAndDetail dto)
        {
            await _service.InsertAsync(dto);
            return this.JsonSuccess();
        }
        /// <summary>
        /// 对手动增加的数据进行修改
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost("Update")]
        [PermissionFilter(nameof(YH_ScreeningController) + "_" + nameof(YH_ScreeningController.UpdateAsync), AuthorizationConst.SAVE)]
        public async Task<IActionResult> UpdateAsync(YH_ProjectAndDetail dto)
        {
            await _service.UpdateAsync(dto);
            return this.JsonSuccess();
        }
        /// <summary>
        /// 对手动增加的数据进行修改
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet("Remove")]
        [PermissionFilter(nameof(YH_ScreeningController) + "_" + nameof(YH_ScreeningController.RemoveAsync), AuthorizationConst.SAVE)]
        public async Task<IActionResult> RemoveAsync(Guid id)
        {
            await _serviceDetail.DeleteAsync(id);
            return this.JsonSuccess();
        }

        /// <summary>
        /// 排查上报
        ///</summary>
        /// <param name="dto"></param>
        /// <returns></returns>

        [HttpPost("Report")]
        [PermissionFilter(nameof(YH_ScreeningController) + "_" + nameof(YH_ScreeningController.ReportAsync), AuthorizationConst.SAVE)]
        public async Task<IActionResult> ReportAsync(YH_ScreeningDetailDto dto)
        {
            var result = await _service.ReportAsync(dto);
            if (result.result == "true")
            {
                var detailEntity = (YH_ScreeningDetail)result.data;
                //利用detailEntity发消息
                //....
                return this.JsonSuccess(string.Empty);
            }
            else
            {
                return this.JsonFaild(result.message);
            }
        }


        /// <summary>
        /// DeleteMuti
        ///</summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        [HttpPost("DeleteMuti")]
        [PermissionFilter(nameof(YH_ScreeningController) + "_" + nameof(YH_ScreeningController.DeleteMutiAsync), AuthorizationConst.DELETE)]
        public async Task<IActionResult> DeleteMutiAsync([FromBody]Guid[] ids)
        {

            await _service.DeleteBatchAsync(ids);
            return this.JsonSuccess();
        }


        /// <summary>
        /// 根据ID获取信息
        ///</summary>
        /// <param name="id"></param>
        /// <returns></returns>

        [HttpGet("Get")]
        public async Task<IActionResult> Get(Guid id)
        {
            var dto = await _service.GetAsync(id);
            if (dto == null) return this.JsonFaild("未找到对应数据:" + id);
            //拼接参与人员姓名
            var str = "";
            dto.YH_ScreeningUser.ToList().ForEach(a =>
            {
                str += a.UserText + ",";
            });
            if (str.Length > 0)
                str = str.Substring(0, str.Length - 1);
            dto.Participant = str;


            dto.YH_ProjectAndDetail = new List<YH_ProjectAndDetail>();
            dto.YH_ScreeningProject.ToList().ForEach(project =>
            {
                project.YH_ScreeningDetail.ToList().ForEach(detail =>
                {
                    detail.ScreeningDetailId = detail.Id;
                    var standingBookDto = _service.CheckStandingBook(detail.AreaID, detail.StandardID);
                    dto.YH_ProjectAndDetail.Add(new YH_ProjectAndDetail()
                    {
                        Id = detail.Id,
                        ScreeningId = dto.Id,
                        Project = project.Project,
                        Region = detail.AreaID,
                        RegionName = detail.AreaName,
                        AreaName = detail.AreaName,
                        Remark = project.Remark,
                        ScreeningProjectId = project.Id,
                        ScreeningDetailId = detail.Id,
                        SearchMajorCode = detail.SearchMajorCode,
                        StandardID = detail.StandardID,
                        StandardContent = detail.StandardContent,
                        Type = detail.Type,
                        CreateFactory = detail.CreateFactory,
                        RiskLevel = detail.RiskLevel,
                        RiskLevelText = detail.RiskLevelText,
                        result = detail.result,
                        BookCode = standingBookDto != null ? standingBookDto.StandingBookNo : "无",
                        StandingBookState = standingBookDto?.State,
                        StandingBookStateText = standingBookDto != null ? "(" + standingBookDto.StateText + ")" : "",
                        IsNotPlan = detail.IsNotPlan

                    });
                });
            });
            return this.JsonSuccess(dto);
        }


        /// <summary>
        /// 根据详细信息ID获取详细信息
        ///</summary>
        /// <param name="id"></param>
        /// <returns></returns>

        [HttpGet("GetDetail")]
        public async Task<IActionResult> GetDetail(Guid id)
        {
            var dto = await _serviceDetail.GetAsync(id);
            if (dto.YH_StandingBook == null)
            {
                dto.YH_StandingBook = new YH_StandingBookDto()
                {
                    Discoverer = UserIdentity.Id,
                    DiscovererText = UserIdentity.Name
                };
            }
            if (dto == null) return this.JsonFaild("未找到对应数据:" + id);
            return this.JsonSuccess(dto);
        }
        /// <summary>
        /// 导出
        ///</summary>
        /// <param name="pagingQueryModel"></param>
        /// <returns></returns>

        [HttpPost("Export")]
        [PermissionFilter(nameof(YH_ScreeningController) + "_" + nameof(YH_ScreeningController.Export), AuthorizationConst.EXPORT)]
        public async Task<IActionResult> Export(PagingModel<YH_ScreeningDto> pagingQueryModel)
        {
            var fileName = await _service.Export(pagingQueryModel);
            if (string.IsNullOrWhiteSpace(fileName))
                return this.JsonFaild(NULL_DATA_FOR_EXCEL_EXPORT);
            return this.JsonSuccess(fileName);
        }
        #endregion


    }
}
